﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using System.Data;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using Pcm.Retail.Client;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine.UI.DataTypes.Navigation;
using CdcSoftware.Pivotal.Engine.Client.Types;
using CdcSoftware.Iaf.SmartClient.Message;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Authorization : FormClientTask
    {
        #region Class Variables
        #endregion

        /// <summary>
        /// Gets fored on form initialization.
        /// </summary>
        public override void OnFormInitialized()
        {
            try
            {
                base.OnFormInitialized();

                this.AddRemoveButtons();

                //Remove the taskpads.
                if (this.TaskPad != null)
                    this.TaskPad.Visible = false;

                this.FormControl.GetControlByName("Staff_Code").Focus();

                //Show the Void Receipt and the Re-print receipt group boxes according to the logic.
                //If there is no UserDefinedParameter, then it is from Tender button click or Process sale.
                //If there is UserDefinedParameter parameter, then
                //  If the value is true, then it is triggered from Void button.
                //  If the value is false, then it is triggered from Re-Print button.
                if (this.TransitionPointParameter.UserDefinedParametersNumber == 7 &&
                    TypeConvert.ToBoolean(this.TransitionPointParameter.GetUserDefinedParameter(7)))
                {
                    //From Void button click.
                    EnableDisableVoidReprint(true);
                }
                else if (this.TransitionPointParameter.UserDefinedParametersNumber == 7 && this.TransitionPointParameter.GetUserDefinedParameter(7) != null &&
                    !TypeConvert.ToBoolean(this.TransitionPointParameter.GetUserDefinedParameter(7)))
                {
                    //From Re-Print button click.
                    EnableDisableVoidReprint(false);
                }
                else
                {
                    EnableDisableVoidReprint(null);
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Enable/Disable the Void/Reprint group boxes and set the required property.
        /// </summary>
        /// <param name="isVoid">If null, then both needs to be invisible, true makes the Void only visible and false makes the Reprint only visible.</param>
        private void EnableDisableVoidReprint(bool? isVoid)
        {
            ((PivotalDropDown)this.FormControl.GetControlByDataName("RE_Void_Reason")).Required = TypeConvert.ToBoolean(isVoid);
            ((PivotalDropDown)this.FormControl.GetControlByDataName("RE_RePrint_Reason")).Required = (isVoid == null) ? false : !TypeConvert.ToBoolean(isVoid);
            
            ((PivotalGroupBox)this.FormControl.GetControlByName("Void_Receipt")).Visible = TypeConvert.ToBoolean(isVoid);
            ((PivotalGroupBox)this.FormControl.GetControlByName("Reprint_Receipt")).Visible = (isVoid == null) ? false : !TypeConvert.ToBoolean(isVoid);
        }

        /// <summary>
        /// Saves the record.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.9.1        2011-11-21      DS              Initial version for Retail.                                                
        /// </history>
        public override bool SaveRecord()
        {
            try
            {
                if (this.DataSet.Tables["RE_Authorization_Order_Id"].AsEnumerable().Count(a => (TypeConvert.ToBoolean(a["Authorized"]) == true &&
                    a["RE_Authorized_By_Id"] == DBNull.Value)) != 0)
                {
                    PivotalMessageBox.Show("Please Authorize the events checked.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                return base.SaveRecord();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
            return false;
        }

        /// <summary>
        /// Fire the event on change of Status.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.1     2011-11-21      DS          Initial version for Retail.
        /// </history>
        public virtual void GridCheckedChanged(object sender, EventArgs args)
        {
            try
            {
                DataGridViewCellEventArgs dgEventArgs = args as DataGridViewCellEventArgs;
                this.DataSet.Tables["RE_Authorization_Order_Id"].Rows[dgEventArgs.RowIndex]["RE_Authorized_By_Id"] = DBNull.Value;
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        #region Private Functions

        private void AddRemoveButtons()
        {
            try
            {
                ButtonBarButton btnCancel = this.ButtonBar.Buttons["Cancel"];
                this.ButtonBar.Buttons.Clear();                

                ButtonBarButton btnAuthorize = new ButtonBarButton();
                btnAuthorize.DisplayName = "Authorize";
                btnAuthorize.ImageName = "Authorize";
                btnAuthorize.Name = "Authorize";
                this.ButtonBar.Buttons.Add(btnAuthorize);
                Command strcommand = Globals.SystemClient.UserProfile.GetMetaItem<Command>("RE_Authorization.AuthorizeButtonClick");
                IActionService actionService = ClientContext.ClientAPIService.GetService<IActionService>();
                if (strcommand.ClientTaskId != null)
                {
                    CdcSoftware.Pivotal.Engine.Client.Types.CommandHandler strcommandHandler = Globals.SystemClient.UserProfile.GetMetaItem<CdcSoftware.Pivotal.Engine.Client.Types.CommandHandler>(strcommand.CommandHandlerId);
                    IClientTaskActionTarget clientTaskActionTarget1 = actionService.CreateActionTarget<IClientTaskActionTarget>();
                    clientTaskActionTarget1.ClientTask = strcommand.ClientTaskId;
                    clientTaskActionTarget1.ClientTaskMethod = strcommandHandler.MethodName;
                    IAction action1 = actionService.CreateAction(string.Empty, ActionCommand.Show, ActionContent.ClientTask, clientTaskActionTarget1);
                    btnAuthorize.Action = (CommandMessage)action1;
                }

                this.ButtonBar.Buttons.Add(btnCancel);
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }
        #endregion
    }
}
